package main.sevices;

import java.io.Serializable;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import main.common.Utility;
import main.enums.JsonResponseStatus;
import main.models.JsonResponseModel;
import main.security.UserSession;

@Named("UserServices")
@SessionScoped
@Path("/userservice")
@Produces({"application/json"})
@Consumes({"application/json"})
public class UserServices implements Serializable {

	/**
	 * GUID for Serializable.
	 */
	private static final long serialVersionUID = -1299365504716099787L;
	
	@Inject
	private UserSession userBean;
	
	public UserServices() {
		
	}
	
	@PostConstruct
	public void init() {
		
	}
	
	@POST
	@Path("/login")
	public JsonResponseModel login(Map<String,String> loginMap, @Context HttpServletRequest request) {
		String requestAddr = request.getRemoteAddr();
		
		if(Utility.isLocalHost(requestAddr)) {
			if(userBean.attemptSignin(loginMap.get("userName"), loginMap.get("password"))) {
				return new JsonResponseModel(JsonResponseStatus.SUCCESS, "", userBean.getCurrentUser());
			}
			else {
				return new JsonResponseModel(JsonResponseStatus.INVALID, "No user found for username [" + loginMap.get("userName") + "] or invalid username/password combination.", null);
			}
		}
		
		return new JsonResponseModel(JsonResponseStatus.INVALID, "[/login] Method is Only Available for Developer Use.", null);
	}
	
	@GET
	@Path("/user")
	public JsonResponseModel getUser() {
		if(userBean.getCurrentUser() != null) {
			return new JsonResponseModel(JsonResponseStatus.SUCCESS, "", userBean.getCurrentUser());
		}
		else {
			return new JsonResponseModel(JsonResponseStatus.INVALID, "There is no user currently logged in.", null);
		}
	}
	
}
